let branchEl = document.querySelector(".branch");
let footerEl = document.querySelector("footer");
let everyBoxEl = document.querySelector(".everyBox");

//获取头部的当月时间元素并设置成当月
let headTimeEl = document.querySelector(".userandtime_inp");
headTimeEl.value = yearMonth(Number(new Date()));
headTimeEl.classList.contains;

//获取个人信息页、统计、日期查询页面元素并跳转
let headEl = document.querySelector("header");
headEl.onclick = function (e) {
  console.log(e.target);
  if (e.target.classList.contains("userimg")) {
    window.location.href = "./userMmt.html";
  } else if (e.target.classList.contains("dateimg")) {
    window.location.href = "./checkDailyBill.html";
  } else if (e.target.classList.contains("chartimg")) {
    window.location.href = "./graphStatistics.html";
  }
};

//获取收入支出总计元素
let outInpEl = document.querySelector(".month_out");
let inInpEl = document.querySelector(".month_in");
let sumInpEl = document.querySelector(".month_sum");

//获取总预算相关元素
let budgetEl = document.querySelector(".budget");
let surplusEl = document.querySelector(".surplus");
let sunmoneyEl = document.querySelector(".sunmoney");
let rollEl = document.querySelector(".roll");

//总额、剩余、滑动块最大值从本地获取
sunmoneyEl.value = localStorage.getItem("sunmoney");
surplusEl.value = localStorage.getItem("surplus");
rollEl.max = localStorage.getItem("sunmoney");
rollEl.disabled = "true";
rollEl.value = surplusEl.value;

let backgroundEl = document.querySelector(".background");
let changebudgetEl = document.querySelector(".changebudget");

let changebudgetBoxEl = document.querySelector(".changebudget_box input");
let confirmEl = document.querySelector(".confirm");

//切换修改总预算页面
budgetEl.addEventListener("click", changeBudget);

//确定修改总预算
confirmEl.addEventListener("click", confirmBut);

//弹出修改总预算页面
function changeBudget() {
  backgroundEl.classList.toggle("showbackground");
  changebudgetEl.classList.toggle("showchangebudget");
  changebudgetBoxEl.value = sunmoneyEl.value;
}

//确定修改总预算
function confirmBut() {
  backgroundEl.classList.toggle("showbackground");
  changebudgetEl.classList.toggle("showchangebudget");
  sunmoneyEl.value = changebudgetBoxEl.value;
  localStorage.setItem("sunmoney", changebudgetBoxEl.value);

  //设置预算滑动块的最大值
  rollEl.max = changebudgetBoxEl.value;
}

//设置尾部的添加账单的消失和出现
window.onscroll = function () {
  if (window.scrollY > 150) {
    footerEl.style.display = "none";
  } else {
    footerEl.style.display = "block";
  }
};

//设置跳转到记账页面
footerEl.onclick = function () {
  window.location.href = "./bookKeeping.html";
};

//将账本分天存储在二维数组里面
async function everyExpenditure() {
  let res = await getSciFiBooks();

  if (res.length == 1) return createEveryBox();

  let newRes = [],
    arr = [];

  res.forEach((item, index) => {
    if (index + 1 == res.length) {
      arr.push(res[index]);
      newRes.push(arr);
      return;
    }
    if (new Date(item.time).getDate() == new Date(res[index + 1].time).getDate()) {
      arr.push(item);
    } else {
      arr.push(item);
      newRes.push(arr);

      arr = [];
    }
  });

  return newRes;
}

//获取当月的本地存储数据
async function getSciFiBooks() {
  const Res = await getData((year = new Date().getFullYear()), new Date().getMonth() + 1);

  return Res;
}

//按天渲染每一天数据，并计算月支出月收入渲染到页面顶端的总计
async function createEveryBox() {
  let arr = await everyExpenditure();
  let arrNum = [];

  for (let index = 0; index < arr.length; index++) {
    let item = arr[index];
    let arrC;
    arrC = await everyday(item, index);
    arrNum.push(arrC);
  }
  let outInp = 0,
    inInp = 0,
    sumInp = 0;
  for (let i = 0; i < arrNum.length; i++) {
    inInp += arrNum[i][0];
    outInp += arrNum[i][1];
    outInp += arrNum[i][2];
    outInp -= arrNum[i][3];
  }

  sumInp = Number((inInp - outInp).toFixed(2));

  inInpEl.value = inInp;
  outInpEl.value = outInp;
  sumInpEl.value = sumInp;

  //设置预算的剩余值
  surplusEl.value = localStorage.getItem("sunmoney") - Number(outInp);
  localStorage.setItem("surplus", localStorage.getItem("sunmoney") - Number(outInp));

  //设置预算滑动块位置
  rollEl.value = localStorage.getItem("sunmoney") - Number(outInp);

  return arrNum;
}

//渲染一天的数据
async function everyday(arr, index) {
  let html = `    <div class="everyday${index} everyday">
  <div class="title">
    <div><span>${formatTimeStamp(arr[0].time)}</span></div>
    <div class="in_up"></div>
  </div>
  <ul class="type">
  </ul>
</div>`;

  everyBoxEl.innerHTML += html;

  let ulEl = document.querySelector(`.everyday${index} .type`);
  let inUpEl = document.querySelector(`.everyday${index} .in_up`);

  //记录账单是否有收入、支出或报销类型
  let income = false,
    expend = false,
    reimbursement = false;

  trueReimbursed = 0;
  incomeSum = 0;
  expendSum = 0;
  reimbursementSum = 0;

  for (const item of arr) {
    //渲染对应数据
    if (item.moneyType == true && item.reimbursement == false) {
      incomeSum += Number(item.money);
      income = true;

      let cHtml = `<li>
      <div>
        <div><span style="background-color: #2dbb7e"></span></div>
        <div><span>${item.consumeType}</span><span>${item.annotation}</span></div>
      </div>
      <div style="color: #2dbb7e"><span>+</span><span>${item.money}</span></div>
    </li>`;
      ulEl.innerHTML += cHtml;
    } else if (item.moneyType == false && item.reimbursement == false) {
      expendSum += Number(item.money);
      expend = true;

      let cHtml = `<li>
      <div>
        <div><span style="background-color: #eb585e"></span></div>
        <div><span>${item.consumeType}</span><span>${item.annotation}</span></div>
      </div>
      <div style="color: #eb585e"><span>-</span><span>${item.money}</span></div>
    </li>`;
      ulEl.innerHTML += cHtml;
    } else if (item.reimbursement == true && item.isReimbursed == false) {
      reimbursementSum += Number(item.money);
      reimbursement = true;

      let cHtml = `<li>
      <div>
        <div><span style="background-color: #3694fa"></span></div>
        <div><span>${item.consumeType}</span><span>${item.annotation}</span></div>
      </div>
      <div style="color: #3694fa"><span></span><span>${item.money}</span></div>
    </li>`;
      ulEl.innerHTML += cHtml;
    } else if (item.reimbursement == true && item.isReimbursed == true) {
      reimbursementSum += Number(item.money);
      reimbursement = true;

      //记录已报销账单，方便记录月支出
      trueReimbursed += Number(item.money);

      let cHtml = `<li>
      <div>
        <div><span style="background-color: #3694fa"></span></div>
        <div><span class = "del">${item.consumeType}</span><span>${item.annotation}</span></div>
      </div>
      <div style="color: #3694fa"><span></span><span>${item.money}</span></div>
    </li>`;
      ulEl.innerHTML += cHtml;
    }

    //判断是否报销以此判断月支出是多少
    else if (item.reimbursement == true && item.isReimbursed == true) {
    }
  }

  if (income == true) {
    //创建收入元素
    let income = document.createElement("span");
    let span1 = document.createElement("span");
    //获取收入总金额

    span1.textContent = incomeSum;
    income.classList.add("income");
    income.textContent = "收入:";
    inUpEl.append(income);
    income.after(span1);
  }
  if (expend == true) {
    //创建支出元素
    let expend = document.createElement("span");
    let span2 = document.createElement("span");
    //获取支出总金额

    span2.textContent = expendSum;
    expend.classList.add("expend");
    expend.textContent = "支出:";
    inUpEl.append(expend);
    expend.after(span2);
  }
  if (reimbursement == true) {
    //创建报销元素
    let reimbursement = document.createElement("span");
    let span3 = document.createElement("span");
    //获取报销总金额

    span3.textContent = reimbursementSum;
    reimbursement.textContent = "报销:";
    reimbursement.classList.add("reimbursement");
    inUpEl.append(reimbursement);
    reimbursement.after(span3);
  }
  let arrNum = [incomeSum, expendSum, reimbursementSum, trueReimbursed];
  return arrNum;
}

//近七天柱状图
chart();
async function chart() {
  let aa = await createEveryBox();
  let arr = [];

  for (let i = 0; i < aa.length; i++) {
    arr.push(Number(aa[i][1]));
  }

  while (arr.length < 7) {
    arr.push(Number(0));
  }

  let month = new Date().getMonth() + 1;
  let date = new Date().getDate();

  let myChart = echarts.init(document.querySelector(".pay .statistics"));
  let option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "none",
      },
      triggerOn: "click",
      position: "lef",
    },
    //修改图表大小
    grid: {
      left: "5%",
      right: "4%",
      bottom: "0%",
      top: "8%",
      containLabel: true,
    },
    xAxis: [
      {
        type: "category",
        data: [
          `${month}-${date}`,
          `${month}-${date - 1}`,
          `${month}-${date - 2}`,
          `${month}-${date - 3}`,
          `${month}-${date - 4}`,
          `${month}-${date - 5}`,
          `${month}-${date - 6}`,
        ],
        axisTick: {
          alignWithLabel: true,
        },
        axisLabel: {
          color: "#999",
          fontSize: "12",
        },
        axisTick: {
          show: false,
        },
      },
    ],
    yAxis: [
      {
        type: "value",
        axisTick: {
          show: false,
        },
        splitLine: {
          show: false,
        },
      },
    ],
    series: [
      {
        name: "支出",
        type: "bar",
        barWidth: "30%",
        itemStyle: {
          //修改柱子圆角
          barBorderRadius: [20, 20, 0, 0],
        },
        data: arr,
      },
    ],
  };

  myChart.setOption(option);
  myChart.resize({
    height: 100,
    // width: 300,
  });
}

//转化时间戳成年月日
function formatTimeStamp(timeStamp) {
  timeStamp = parseInt(timeStamp);
  const time = new Date(timeStamp);
  // const year = time.getFullYear();
  let month = time.getMonth() + 1;
  let date = time.getDate();

  month = month < 10 ? "0" + month : month;
  date = date < 10 ? "0" + date : date;

  return `${month}-${date}`;
  // return `${year}-${month}-${date}`;
}

//转化年月函数
function yearMonth(timeStamp) {
  timeStamp = parseInt(timeStamp);
  const time = new Date(timeStamp);
  const year = time.getFullYear();
  let month = time.getMonth() + 1;

  month = month < 10 ? "0" + month : month;

  return `${year}-${month}`;
}
